***CAMS***

use "${original}randcams_2001_2015v2.dta", clear

*** --- copy and clean variable labels --- ***
ren *,upper
foreach v of var * { 
	local l`v' : variable label `v'
	local l0`v': subinstr local l`v' "`v':" "",all
	local l1`v': subinstr local l0`v' "`v': " "",all

	foreach i of numlist 12/5 {
	local l2`v': subinstr local l1`v' "W`i' " "",all
	}
}
ren *,lower
foreach i of numlist 12/5 {
ren h`i'* *__h__`i'
} 
ren incamsc* incamsc__*

ren *__12 *2014
ren *__11 *2012
ren *__10 *2010
ren *__9 *2008
ren *__8 *2006
ren *__7 *2004
ren *__6 *2002
ren *__5 *2000

*** --- store unique stub names throughout all waves in macro to accomodate reshape --- ***
unab vars: *2014 *2012 *2010 *2008 *2006 *2004 *2002 *2000
local stub1: subinstr local vars "2014" "",all
local stub2: subinstr local stub1 "2012" "",all
local stub3: subinstr local stub2 "2010" "",all
local stub4: subinstr local stub3 "2008" "",all
local stub5: subinstr local stub4 "2006" "",all
local stub6: subinstr local stub5 "2004" "",all
local stub7: subinstr local stub6 "2002" "",all
local stub8: subinstr local stub7 "2000" "",all
local uniquestubs: list uniq stub8

*** --- perform the actual reshape --- ***
reshape long `uniquestubs' , i(hhidpn) j(year)

*** --- store variable names in macro and clean macro for relabeling --- ***
ren *,upper
unab allvars__h: *__H
local allvars_h: subinstr local allvars__h "__H" "",all

*** --- relabel variables that lost label in reshape --- ***
foreach v of local allvars_h { 
	foreach y of numlist 5/12 {
			local L`v'__H : variable label `v'__H
			if `"`L`v'__H'"' == "" & `"`l2H`y'`v''"' != "" { 
				label var `v'__H `"`l2H`y'`v''"' 
			}
	}
}

*** --- attach cleaned label to variables unaffected by reshape --- ***
unab allvars: _all
local restvars: list allvars - allvars__h
foreach v of local restvars {
label var `v' `"`l1`v''"' 
}

ren *,lower
ren *__h cams_*

save randcams.dta, replace

use sample_chtr,clear
merge 1:1 hhidpn year using randcams.dta, gen(cams) keep(1 3)
save sample_cams,replace

*Erase temporary datasets
erase randcams.dta
erase sample_chtr.dta